// robot_tcp_server.h
#ifndef ROBOT_TCP_SERVER_H
#define ROBOT_TCP_SERVER_H

#include <QTcpServer>
#include <QTcpSocket>
#include <QMap>
#include <QTimer>
#include <QObject>
#include <QJsonObject>
#include <QJsonDocument>
#include <memory>
#include "../include/seer/SCHeadData.h"
#include "../include/global_logger.h"
#include <rclcpp/rclcpp.hpp>

class RobotTCPServer : public QObject, public rclcpp::Node
{
    Q_OBJECT

public:
    explicit RobotTCPServer(QObject *parent = nullptr);
    ~RobotTCPServer();
    
    bool startServer(quint16 port);
    void stopServer();

private slots:
    void onNewConnection();
    void onClientDisconnected();
    void onReadyRead();
    void onSendResponseTimeout();

private:

    // TCP服务器
    QTcpServer* m_tcpServer;
    QMap<QTcpSocket*, QTimer*> m_clientTimers;
    QMap<QTcpSocket*, QByteArray> m_clientBuffers;
    
    void processClientRequest(QTcpSocket* clientSocket, const QByteArray& requestData);
    void sendResponse(QTcpSocket* clientSocket, uint16_t cmd, const QByteArray& jsonData, const QByteArray& binaryData, uint16_t reqId);
    void handleCommand(QTcpSocket* clientSocket, uint16_t cmd, const QJsonObject& json, uint16_t reqId);
    QByteArray createResponseData(uint16_t cmd, const QByteArray& jsonData, const QByteArray& binaryData, uint16_t reqId);
    
    // 日志打包和发送函数
    bool packageAndSendLogs(QTcpSocket* clientSocket, uint16_t cmd, uint16_t reqId);
    // 日志文件清理函数
    bool clearLogFiles(QTcpSocket* clientSocket, uint16_t cmd, uint16_t reqId);

};

#endif // ROBOT_TCP_SERVER_H